#include<iostream>
#include<vector>
#include<cstdio>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

std::vector<int> data;
const std::string gsep = " ";

enum
{
    OK = 0,
    OPEN_FILE_ERROR, 
};

int savebegin()
{
    std::string name = std::to_string(time(nullptr));
    name += ".backup";
    FILE* fp = fopen(name.c_str(),"w");
    if(fp == nullptr) return OPEN_FILE_ERROR;
    
    std::string datastr;
    for(auto d : data)
    {
        datastr += std::to_string(d);
        datastr += gsep;
    }
    
    fputs(datastr.c_str(), fp);
    fclose(fp);
    return OK;
}

void save()
{
    pid_t id =  fork();
    if(id == 0)
    {
        int code = savebegin();
        exit(code);
    }
    int status = 0;
    pid_t rid = waitpid(id , &status, 0);
    if(rid > 0)
    {
        int code = WEXITSTATUS(status);
        if(code == 0) printf("备份成功, exit code : %d\n",code);
        else  printf("备份失败, exit code : %d\n",code);
    }
    else
    {
        perror("waidpid");
    }
}

int main()
{
    int cnt = 1;
    while(true)
    {
        data.push_back(cnt++);
        sleep(1);
        if(cnt % 10 == 0)
        {
            save();
        }
    }
    return 0;
}

